//
//  QHUtil.m
//  QH_Simplest_Mediadata_Demo
//
//  Created by Anakin chen on 2021/2/7.
//

#import "QHUtil.h"

@implementation QHUtil

+ (NSUInteger)input:(NSString *)name ofType:(nullable NSString *)ext len:(unsigned char **)output {
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:ext];
    NSData *data = [NSData dataWithContentsOfFile:path];
    unsigned char *buf = (unsigned char *)data.bytes;
    *output = buf;
    return data.length;
}

+ (FILE *)output:(NSString *)file {
    NSArray *cacPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [cacPath objectAtIndex:0];
    NSString *p = [cachePath stringByAppendingPathComponent:file];
    const char *out_file_v = [p UTF8String];
    FILE *fp = fopen(out_file_v,"wb+");
    return fp;
}

+ (uint)hexToDecimal:(unsigned char *)buf len:(uint)length {
    uint n = 0;
    for (int i = 0; i < length; i++) {
        uint v = buf[i];
        uint g = 8 * (length - 1 - i);
        n += v * 1 << g;
    }
    return n;
}

+ (FILE *)copy2Caches:(NSString *)name ofType:(nullable NSString *)ext {
    NSArray *cacPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [cacPath objectAtIndex:0];
    NSString *file = [NSString stringWithFormat:@"%@.%@", name, ext];
    NSString *p = [cachePath stringByAppendingPathComponent:file];
    if (![[NSFileManager defaultManager] fileExistsAtPath:p]) {
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:ext];
        if (![[NSFileManager defaultManager] copyItemAtPath:path toPath:p error:nil]) {
            NSLog(@"copy file error");
            return nil;
        }
    }
    const char *in_file_v = [p UTF8String];
    FILE *fp = fopen(in_file_v,"rb+");
    return fp;
}

@end
